import pymysql


class myStu:
    def __init__(self, host, user, pw, dbname):
        self.host = host
        self.user = user
        self.password = pw
        self.dbname = dbname
        # 打开数据库连接
        self.db = pymysql.connect(host=self.host, user=self.user,
                                  password=self.password, db=self.dbname,
                                  charset='utf8')
        # 创建游标，通过连接与数据通信
        self.cursor = self.db.cursor()

    def findAll(self):
        """查询方法"""
        try:
            # 执行sql语句
            self.cursor.execute('select * from student')
            rows = self.cursor.fetchall()
            for row in rows:
                print(row)
        except pymysql.Error as e:
            # 事务回滚
            self.db.rollback()
            print("Mysql Error %d: %s" % (e.args[0], e.args[1]))

    def delinfo(self, id):
        """删除学员信息"""
        try:
            # 执行sql语句
            self.cursor.execute('delete from student where id=%d' % id)
            # 提交到数据库执行
            self.db.commit()
        except pymysql.Error as e:
            # 事务回滚
            self.db.rollback()
            print("Mysql Error %d: %s" % (e.args[0], e.args[1]))

    def insert(self, name, sex, age):
        """添加学员信息"""
        try:
            # 执行sql语句
            self.cursor.execute(
                'insert into student(name,sex,age) values("%s","%s","%d")' % (
                    name, sex, age))
            # 提交到数据库执行
            self.db.commit()
        except pymysql.Error as e:
            # 事务回滚
            self.db.rollback()
            print("Mysql Error %d: %s" % (e.args[0], e.args[1]))

    def __del__(self):
        """析构方法"""
        # 关闭数据库连接
        self.db.close()
